<template>
  <el-dialog
    :title="title"
    :visible.sync="diaAddVisible"
    width="50%"
    @close="close"
  >
    <el-form ref="addform" label-width="120px" :model="form" :rules="rules">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item prop="manager" label="部门负责人">
        <el-select v-model="form.manager" @focus="focusEvent">
          <el-option
            v-for="item in userlist"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="diaAddVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import {
  sysusersimple,
  companyDepartmentPost,
  companydepartmentPut
} from '@/api/departments'
export default {
  name: '',
  props: {
    init: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      diaAddVisible: false,
      mode: 'add',
      itemData: '',
      userlist: [],
      form: {
        code: '', //	string	非必须		部门编码，同级部门不可重复
        introduce: '', //	string	非必须		介绍
        manager: '', //	string	非必须		负责人名称
        name: '', //	string	非必须		部门名称
        pid: '' //	string	非必须		父级部门ID
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              const tempArr = this.init.filter((item) => {
                // return item.pid === this.itemData.id
                if (this.mode === 'add') {
                  return item.pid === this.itemData.id
                } else if (this.mode === 'edit') {
                  return (
                    item.pid === this.itemData.pid &&
                    item.id !== this.itemData.id
                  )
                }
              })
              console.log('tempArr', tempArr)
              const bol = tempArr.some((item) => {
                return item.name === value
              })
              bol ? callback(new Error('部门名称重名')) : callback()
            }
          }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              const bol = this.init.some((item) => {
                // return item.code === value
                if (this.mode === 'add') {
                  return item.code === value
                } else if (this.mode === 'edit') {
                  return item.code === value && item.id !== this.itemData.id
                }
              })
              bol ? callback(new Error('部门编码重复')) : callback()
            }
          }
        ],
        manager: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    title() {
      return {
        add: '新增部门',
        edit: '编辑部门'
      }[this.mode]
    }
  },
  mounted() {
    this.$bus.$on('showDown', (bol, itemData, mode) => {
      console.log(111)
      this.diaAddVisible = bol
      this.itemData = itemData
      this.form.pid = itemData.id
      this.mode = mode
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(itemData))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('showDown')
  },
  created() {},
  methods: {
    close() {
      this.$refs.addform.resetFields()
      this.form = {
        code: '', //	string	非必须		部门编码，同级部门不可重复
        introduce: '', //	string	非必须		介绍
        manager: '', //	string	非必须		负责人名称
        name: '', //	string	非必须		部门名称
        pid: '' //	string	非必须		父级部门ID
      }
    },
    // 获取简单员工列表
    async focusEvent() {
      if (this.userlist.length === 0) {
        const res = await sysusersimple()
        console.log(res)
        this.userlist = res.data
      }
    },
    // 点击确定添加
    submit() {
      this.$refs.addform.validate(async(valid) => {
        if (valid) {
          if (this.mode === 'add') {
            await companyDepartmentPost(this.form)
            this.$message.success('添加成功')
          } else if (this.mode === 'edit') {
            await companydepartmentPut(this.form)
            this.$message.success('编辑成功')
          }

          this.diaAddVisible = false
          this.$emit('getData')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped></style>
